package ase;




import java.io.*;
import java.net.*;

public class TCPClient
{
	private String ip;
	private int port;
	private DataOutputStream outToServer;
	private BufferedReader inFromServer;
	private Socket clientSocket;
	private Ui ui;

	public TCPClient(String ip, int port, Ui ui)
	{
		this.ip = ip;
		this.port = port;
		this.ui = ui;
	}

	public void connect() throws Exception
	{	
		clientSocket = new Socket(ip, port);
		outToServer = new DataOutputStream(clientSocket.getOutputStream());
		inFromServer = new BufferedReader(new InputStreamReader(
				clientSocket.getInputStream()));
		System.out.println(inFromServer.readLine());
	}

	public String command(String input) throws IOException{
		outToServer.writeBytes(input + "\r\n");
		ui.printToConsole("Sending command: " + input);
		String in = inFromServer.readLine();
		ui.printToConsole("Message from return "+in);
		if(in.startsWith("RM20 B") || in.startsWith("RM49 B")){
			ui.printToConsole("Waiting for next input");
			in = inFromServer.readLine();
		}
		return in;
	}	
	public String waitForInput() throws IOException{
		return inFromServer.readLine();	
	}
	public void closeConnection() throws IOException{
		clientSocket.close();
		outToServer.close();
		inFromServer.close();
	}
}
